import { defineStore } from "pinia";
import { store } from "@/store";
import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageSession } from "@pureadmin/utils";
import { getLogin, getUserInfo } from "@/api/user";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { setToken, removeToken, userInfoKey, setUserInfo } from "@/utils/auth";

import { type userInfoType } from "@/api/types";
// 查询用户省市区数据

export const useUserStore = defineStore({
  id: "pure-user",
  state: () => ({
    // 用户信息
    userInfo: storageSession().getItem<userInfoType>(userInfoKey)
  }),
  actions: {
    /** 设置用户信息 */
    SET_USERINFO(data: userInfoType) {
      this.userInfo = data;
    },

    /** 登入 */
    async loginByUsername(data) {
      return new Promise<{ accessToken: string }>((resolve, reject) => {
        getLogin(data)
          .then(async res => {
            // console.log("res:", res);
            if (res.accessToken) {
              // 设置token
              setToken({ accessToken: res.accessToken });
              // 获取用户信息
              const userInfoRes = await getUserInfo();

              if (userInfoRes) {
                setUserInfo(userInfoRes);
                this.userInfo = userInfoRes;
                resolve(res);
              } else {
                resolve(res);
              }
            } else {
              resolve(res);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.userInfo = undefined;
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
